<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="旧文件名" prop="oldName">
        <el-input
          v-model="queryParams.oldName"
          placeholder="请输入旧文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件大小" prop="size">
        <el-input
          v-model="queryParams.size"
          placeholder="请输入文件大小"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择文件类型" clearable>
          <el-option
            v-for="dict in dict.type.file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="是否是目录" prop="isDir">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.isDir"-->
      <!--          placeholder="请输入是否是目录"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="创建者" prop="createId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.createId"-->
      <!--          placeholder="请输入创建者"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="更新者" prop="updateId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.updateId"-->
      <!--          placeholder="请输入更新者"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload el-icon--right"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['disk:file:add']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="single"
          @click="handleDownload"
        >下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddDir"
          v-hasPermi="['disk:file:add']"
        >新建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['disk:file:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['disk:file:remove']"
        >删除</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['disk:file:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-share"
          size="mini"
          :disabled="multiple"
          @click="handleShare"
          v-hasPermi="['disk:file:share']"
        >分享</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-picture"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleSetCover"-->
      <!--          v-hasPermi="['disk:file:edit']"-->
      <!--        >设置封面</el-button>-->
      <!--      </el-col>-->

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-picture"
          size="mini"
          :disabled="single"
          @click="handleSetCover"
          v-hasPermi="['disk:file:edit']"
          v-show="showSetCover"
        >{{ coverButtonText }}</el-button>
      </el-col>



      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-arrow-left"
          size="mini"
          @click="handleSkip(0)"
          v-hasPermi="['disk:file:add']"
        ></el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-arrow-right el-icon--right"
          size="mini"
          @click="handleSkip(1)"
          v-hasPermi="['disk:file:add']"
        ></el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="dataRefresh"></right-toolbar>
    </el-row>

    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>
        <el-link :underline="false" @click="skipCrumbs(0)">根目录</el-link>
      </el-breadcrumb-item>

      <el-breadcrumb-item v-for="(item,index) in crumbsList" :key="index">
        <el-link :underline="false" @click="skipCrumbs(item.id)">{{item.name}}</el-link>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <el-main style="height: 100%" v-loading="loading">
      <el-checkbox-group v-model="checkboxIds" @change="handleSelectionChange">
        <div style="margin-left: 20px" v-for="(itme,index) in fileList" :key="index">
          <div style="float: left;width: 120px;height: 130px;margin-left: 25px;margin-right: 25px;margin-top: 20px;position: relative;">
            <el-checkbox-button  v-if="itme.isDir===1" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">
              <div @dblclick="checkboxOndblclick(itme)" class="grid-content bg-purple">
                <img style="width: 100px;height: 100px" src="@/assets/images/dir.png"/>
                <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)" style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>{{itme.name}}</div>
              </div>
            </el-checkbox-button>
            <!--                <el-checkbox-button  v-if="itme.isDir===0&&itme.type===0" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">-->
            <!--                  <div class="grid-content bg-purple">-->
            <!--                    <image-preview :src="itme.url" :width="100" :height="100"/>-->
            <!--                    <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)" style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>{{itme.name}}</div>-->
            <!--                  </div>-->
            <!--                </el-checkbox-button>-->
            <el-checkbox-button
              :class="{
                'cover-highlight': isCoverFile(itme),
                'video-cover-highlight': isVideoCoverFile(itme)
              }"
              v-if="itme.isDir===0&&itme.type===0"
              @change="handleCheckboxChange"
              :label="itme.id"
              :key="itme.id"
              size="medium"
            >
              <div class="grid-content bg-purple">
                <!-- 添加封面标识图标 -->
                <i v-if="isCoverFile(itme)" class="ri-checkbox-circle-fill cover-icon"></i>
                <!-- 添加视频封面标识图标 -->
                <i v-if="isVideoCoverFile(itme)" class="ri-video-fill video-cover-icon"></i>
                <image-preview :src="itme.url" :width="100" :height="100"/>
                <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)" style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>
                  {{isCoverFile(itme) ? itme.name.replace('封面：', '') : itme.name}}
                </div>
                <!-- 显示对应视频名称的标记 -->
                <div v-if="isVideoCoverFile(itme)" class="video-cover-label">
                  视频封面: {{getVideoCoverName(itme)}}
                </div>
              </div>
            </el-checkbox-button>
            <!-- 视频 -->
            <el-checkbox-button v-if="itme.isDir===0&&itme.type===1" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">
              <div @dblclick="handlePreview(itme)" class="grid-content bg-purple">
                <!-- 添加外部链接标识 -->
                <i v-if="itme.remark === '外部视频链接'" class="ri-links-line external-link-icon"></i>
                <!-- 查找并显示视频封面 -->
                <image-preview
                  v-if="findVideoCover(itme.name)"
                  :src="findVideoCover(itme.name).url"
                  :width="100"
                  :height="100"
                />
                <img
                  v-else
                  style="width: 100px;height: 100px"
                  src="@/assets/images/video.png"
                />
                <div class="file-name" v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)" style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>
                  {{itme.name}}</div>
              </div>
            </el-checkbox-button>
            <el-checkbox-button  v-if="itme.isDir===0&&itme.type===2" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">
              <div class="grid-content bg-purple">
                <img style="width: 100px;height: 100px" src="@/assets/images/file_open.png"/>
                <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)"  style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>{{itme.name}}</div>
              </div>
            </el-checkbox-button>
            <el-checkbox-button  v-if="itme.isDir===0&&itme.type===3" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">
              <div class="grid-content bg-purple">
                <img style="width: 100px;height: 100px" src="@/assets/images/file_music.png"/>
                <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)" style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>{{itme.name}}</div>
              </div>
            </el-checkbox-button>
            <el-checkbox-button  v-if="itme.isDir===0&&itme.type===4" @change="handleCheckboxChange" :label="itme.id" :key="itme.id" size="medium">
              <div class="grid-content bg-purple">
                <img style="width: 100px;height: 100px" src="@/assets/images/file_open.png" />
                <div v-on:mouseover="mouseEnter(index)" @mouseleave="mouseLeave(index)"  style='width:80px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;'>{{itme.name}}</div>
              </div>
            </el-checkbox-button>
            <div v-if="currentIndex===index" class="Extra-Text">
              <span>文件名：{{ itme.name }}</span><br/>
              <span>
                  文件大小：{{ storageUnitFormat(itme.size) }}  &nbsp;&nbsp;
                  创建时间：{{ parseTime(itme.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}&nbsp;&nbsp;
                  更新时间：{{ parseTime(itme.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                </span>
            </div>
          </div>
        </div>
      </el-checkbox-group>
    </el-main>

    <div style="text-align: center;width: 100%" v-show="total===0">
      该文件夹为空
    </div>

    <pagination v-if="false"
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改文件夹对话框 -->
    <el-dialog :title="title" :visible.sync="openDir" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <!--        <el-form-item label="备注" prop="remark">-->
        <!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <!-- 复合输入框 -->
          <div class="icon-input-wrapper">
            <el-input
              v-model="form.remark"
              placeholder="输入图标类名或从下方选择"
              clearable>
              <template #prefix>
                <i v-if="form.remark" :class="form.remark"></i>
              </template>
            </el-input>
          </div>

          <!-- 图标选择网格 -->
          <div class="icon-grid">
            <div
              v-for="icon in icons"
              :key="icon"
              @click="form.remark = icon"
              :class="{ 'active': form.remark === icon }">
              <el-tooltip :content="icon" placement="top">
                <i :class="icon" style="font-size: 24px; color: #606266"></i>
              </el-tooltip>
            </div>
          </div>
          <div><a href="https://remixicon.com/" target="_blank">图标网址:https://remixicon.com/</a></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDirForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 上传文件对话框 -->
    <el-dialog :title="title" :visible.sync="uploadOpen" width="500px" append-to-body>
      <!-- 添加视频链接输入字段 -->
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="100px" style="margin-bottom: 15px;">
        <el-form-item label="视频链接" prop="videoLink">
          <el-input v-model="uploadForm.videoLink" placeholder="输入视频链接（可选）" clearable>
            <template #prepend>
              <i class="ri-link"></i>
            </template>
          </el-input>
          <div class="el-form-item__tip">如果是外部视频链接，必须上传封面图片</div>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-demo" style="margin-left: 3rem;"
        ref="upload"
        drag
        :action="uploadFileUrl"
        :on-change="handleBeforeUpload"
        :auto-upload="false"
        :file-list="uploadFileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="true"
        :headers="headers"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text" >将文件拖到此处，或<em>点击上传</em></div>
        <!-- 上传提示 -->
        <div class="el-upload__tip" slot="tip" v-if="showTip" style="margin-left: -1.5rem;width: 420px">
          请上传
          <template v-if="fileSize"> 视频MP4大小不超过 <b style="color: #f56c6c">{{ maxVidSize }}MB</b> ,图片大小不超过 <b style="color: #f56c6c">{{ maxPicSize }}KB</b></template>
          <template v-if="fileSize"> 数量不超过 <b style="color: #f56c6c">{{ limit }}</b> </template><br><br>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
          的文件
        </div>
      </el-upload>

      <!-- 增加视频封面选项 -->
      <div v-if="hasImageInUpload || uploadForm.videoLink" style="margin: 15px 20px;">
        <el-checkbox v-model="isVideoCover" @change="handleVideoCoverChange">设置为视频封面</el-checkbox>
        <el-input
          v-if="isVideoCover && !uploadForm.videoLink"
          v-model="videoCoverName"
          placeholder="请输入要添加封面的视频名称"
          style="margin-top: 10px;"
        ></el-input>
        <div v-if="uploadForm.videoLink && !hasImageInUpload" class="el-alert el-alert--warning" style="margin-top: 10px; padding: 8px 16px;">
          <i class="el-icon-warning"></i>
          <span class="el-alert__title">外部视频链接必须上传封面图片</span>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
        <!-- 添加确认按钮，仅在验证通过后显示 -->
        <el-button
          v-if="isValid"
          type="primary"
          @click="handleConfirmSubmit"
        >
          确认提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 修改文件对话框 -->
    <el-dialog :title="title" :visible.sync="updteOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="旧文件名" prop="oldName">
          <el-input v-model="form.oldName" placeholder="请输入旧文件名" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <!--        <el-form-item label="封面" prop="remark">-->
        <!--          &lt;!&ndash; 视频文件显示图片上传 &ndash;&gt;-->
        <!--          <div v-if="form.type === 1">-->
        <!--            <el-upload-->
        <!--              :action="uploadCoverUrl"-->
        <!--              :headers="headers"-->
        <!--              :show-file-list="false"-->
        <!--              :on-success="handleCoverSuccess"-->
        <!--              :before-upload="beforeCoverUpload"-->
        <!--              class="cover-uploader"-->
        <!--              accept="image/png,image/jpeg"-->
        <!--            >-->
        <!--              <div class="cover-preview">-->
        <!--                <image-preview-->
        <!--                  v-if="form.remark"-->
        <!--                  :src="form.remark"-->
        <!--                  :width="160"-->
        <!--                  :height="90"-->
        <!--                  fit="cover"-->
        <!--                />-->
        <!--                <div v-else class="cover-placeholder">-->
        <!--                  <i class="el-icon-plus"></i>-->
        <!--                  <div class="el-upload__text">点击上传封面</div>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--              <div slot="tip" class="el-upload__tip">-->
        <!--                建议尺寸：16:9（如1280x720），支持JPG/PNG格式，大小不超过2MB-->
        <!--              </div>-->
        <!--            </el-upload>-->
        <!--            <image-preview-->
        <!--              v-if="form.remark"-->
        <!--              :src="form.remark"-->
        <!--              :width="100"-->
        <!--              :height="100"-->
        <!--              style="margin-top:10px;border:1px dashed #d9d9d9;"-->
        <!--            />-->
        <!--          </div>-->
        <!--          &lt;!&ndash; 其他文件类型显示图标选择 &ndash;&gt;-->
        <!--          <div v-else>-->
        <!--            <div class="icon-grid">-->
        <!--              <div v-for="icon in icons" :key="icon" @click="form.remark = icon">-->
        <!--                <i :class="icon"></i>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="可自定义编辑" />
          修改视频封面，先上传一张图片，该图片可作为视频封面。<br>
          修改方式：点击你要修改的图片，在其备注框里面输入：视频封面：+ "你要修改的视频名称"
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改分享对话框 -->
    <el-dialog :title="title" :visible.sync="openShare" width="500px" append-to-body>
      <div v-if="shareOk===false">
        <el-form ref="shareFrom" :model="shareFrom" :rules="shareRules" label-width="80px">
          <el-form-item label="分享方式：">
            <el-radio v-model="shareFrom.type" label="0">私密</el-radio>
            <el-radio v-model="shareFrom.type" label="1">公开</el-radio>
          </el-form-item>
          <el-form-item v-if="shareFrom.type==='0'" label="提取码" prop="secretKey">
            <el-radio v-model="shareFrom.secretKeyRadio" label="1">系统生成</el-radio>
            <el-radio v-model="shareFrom.secretKeyRadio" label="2">自定义</el-radio>
            <el-input v-if="shareFrom.secretKeyRadio==='2'" v-model="shareFrom.secretKey" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="过期时间" prop="expirationTime">
            <el-radio v-model="shareFrom.expirationTimeRadio" label="1">永久</el-radio>
            <el-radio v-model="shareFrom.expirationTimeRadio" label="2">自定义</el-radio>
            <el-date-picker v-if="shareFrom.expirationTimeRadio==='2'" clearable
                            v-model="shareFrom.expirationTime"
                            type="datetime"
                            align="right"
                            value-format="yyyy-MM-dd"
                            :picker-options="pickerOptions"
                            placeholder="请选择">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="shareFrom.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitShareForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
      <div v-else>
        <div style="margin-bottom: 20px">
          <div style="margin-top: 10px">
            链接
            <div>{{shareBaseUrl + 'uuid=' +shareResult.uuid}}</div>
          </div>

          <div style="margin-top: 10px" v-if="shareResult.type==='0'">
            提取码
            <el-input v-model="shareResult.secretKey" :disabled="true" />
          </div>

          <div style="margin-top: 10px">
            过期时间
            <div v-if="shareResult.isPermanent">永久</div>
            <div v-else>{{ parseTime(shareResult.expirationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>

          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="shareResult.type==='1'"
            v-clipboard:copy="shareBaseUrl + 'uuid=' + shareResult.uuid + '      ' + shareResult.remark"
            v-clipboard:success="copySuccess"
            v-clipboard:error="copyFailed"
          >复制</el-button>
          <el-button
            v-if="shareResult.type==='0'"
            v-clipboard:copy="shareBaseUrl + 'uuid=' + shareResult.uuid + '   提取码：'+ shareResult.secretKey + '      ' + shareResult.remark"
            v-clipboard:success="copySuccess"
            v-clipboard:error="copyFailed"
          >复制</el-button>
          <el-button
            v-if="shareResult.type==='0'"
            v-clipboard:copy="shareBaseUrl + 'uuid=' + shareResult.uuid + '&secretKey='+shareResult.secretKey   + '      ' + shareResult.remark"
            v-clipboard:success="copySuccess"
            v-clipboard:error="copyFailed"
          >复制(免填提取码)</el-button>
          <el-button @click="cancel">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>


</template>

<script>

import 'remixicon/fonts/remixicon.css';

import {getToken} from "@/utils/auth";
import {addFile, delFile, getFile, listFile, updateFile} from "@/api/disk/file";
import {addShare} from "@/api/disk/share";

export default {

  name: "File",
  dicts: ['file_type'],
  data() {
    return {
      uploadCoverUrl: process.env.VUE_APP_BASE_API + "/disk/file/upload/cover", // 封面专用上传路径
      showSetCover: false,
      coverButtonText: '设置封面',

      // 新增上传表单
      uploadForm: {
        videoLink: ''
      },
      // 上传表单验证规则
      uploadRules: {
        videoLink: [
          { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
        ]
      },

      icons: [
        "ri-file-excel-line", "ri-file-code-line", "ri-file-image-line", "ri-file-music-line", "ri-file-add-line", "ri-file-reduce-line", "ri-file-lock-line", "ri-file-user-line", "ri-file-history-line", "ri-file-warning-line", "ri-file-search-line", "ri-file-excel-fill", "ri-file-code-fill", "ri-file-image-fill", "ri-file-music-fill","ri-file-history-fill","ri-file-video-line", "ri-file-video-fill", "ri-file-shield-line", "ri-file-cloud-line", "ri-file-cloud-fill", "ri-file-settings-line", "ri-file-chart-line", "ri-file-info-line","ri-file-download-line","ri-file-list-line", "ri-file-list-fill", "ri-file-text-line", "ri-file-text-fill", "ri-folder-line", "ri-folder-fill", "ri-file-zip-line", "ri-file-zip-fill", "ri-file-word-line", "ri-file-word-fill", "ri-file-pdf-line", "ri-file-pdf-fill", "ri-file-ppt-line", "ri-file-ppt-fill", "ri-file-search-fill","ri-file-add-fill","ri-file-reduce-fill","ri-file-settings-fill", "ri-file-upload-line", "ri-file-upload-fill", "ri-file-transfer-line", "ri-file-transfer-fill","ri-file-download-fill","ri-file-lock-fill", "ri-file-chart-fill", "ri-file-check-line", "ri-file-check-fill", "ri-file-close-line", "ri-file-close-fill", "ri-file-forbid-line", "ri-file-forbid-fill","ri-file-info-fill", "ri-file-warning-fill", "ri-file-user-fill", "ri-file-shield-fill", "ri-file-damage-line", "ri-file-damage-fill", "ri-file-copy-line", "ri-file-hwp-line", "ri-file-hwp-fill", "ri-file-gif-line", "ri-file-gif-fill", "ri-file-mark-fill", "ri-file-letter-line", "ri-file-letter-fill"
      ],

      isValid: false,
      // 遮罩层
      loading: true,




      // 选中数组
      ids: [],
      checkboxIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      uploadOpen: false,
      openDir: false,
      updteOpen: false,
      // 删除标志时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        oldName: null,
        size: null,
        type: null,
        isDir: null,
        parentId: null,
        createId: null,
        createTime: null,
        updateId: null,
      },
      // 表单参数
      form: {
        remarkText: '',
        remarkIcon: '',
        remark: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/disk/file/upload/"+0,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 数量限制
      limit: 10,
      // 大小限制(MB)
      fileSize: 512,
      maxPicSize:512,
      maxVidSize:100,


      fileType: ["bmp", "gif", "jpg", "jpeg", "png","swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
        "asf", "rm", "rmvb","mp4", "avi", "rmvb","doc", "docx", "xls", "ppt", "txt", "pdf"],
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      },
      number: 0,
      uploadFileList: [],
      shareFrom: {
        secretKeyRadio: "1",
        expirationTimeRadio: "1",
        type: "0"
      },
      openShare: false,
      shareRules: {
        secretKey: [
          { required: true, message: "密钥不能为空", trigger: "blur" }
        ],
        expirationTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" },
          { rangelength: [4-6], message: "密钥长度4-6", trigger: "blur" }
        ],
      },
      shareResult: {},
      shareOk: false,
      shareBaseUrl: '',
      allCrumbsList: [],
      crumbsList: [
      ],
      skipList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
        shortcuts: [{
          text: '三天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }, {
          text: '半月',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 15);
            picker.$emit('pick', date);
          }
        }, {
          text: '一个月',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', date);
          }
        }, {
          text: '半年',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 182.5);
            picker.$emit('pick', date);
          }
        }, {
          text: '一年',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 365);
            picker.$emit('pick', date);
          }
        }]
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      currentIndex: -1,
      // 新增视频封面选项相关变量
      isVideoCover: false,
      videoCoverName: '',
      hasImageInUpload: false,
      currentUploadFile: null
    }
  },
  created() {
    this.queryParams.parentId = 0;
    this.getList();
    this.getConfigKey("font.baseUrl").then(response => {
      this.shareBaseUrl = response.msg + "/external/share/share-list?";
    });
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize || this.limit);
    },
  },
  methods: {

    handleCoverSuccess(res) {
      if (res.code === 200) {
        // 直接使用返回的文件路径作为封面地址
        this.form.remark = res.data.url
        this.$modal.msgSuccess("封面更新成功")
      } else {
        this.$modal.msgError("封面更新失败：" + res.msg)
      }
    },


    isCoverFile(file) {
      return file && file.name && file.name.startsWith('封面：');
    },

    selectIcon(icon) {
      this.form.remarkIcon = icon
      // 如果希望在选中图标时自动添加图标名称到文本中
      // this.form.remarkText += ` ${icon}`

    },

    getIconComponent(iconName) {
      // 将 ri-folder-line 转换为 RiFolderLine 格式
      return iconName
        .split('-')
        .map(word => word[0].toUpperCase() + word.slice(1))
        .join('')
    },

    handleBeforeUpload(file, files) {
      console.log("处理上传文件:", file.name, file);

      try {
        // 校检文件类型
        if (this.fileType) {
          const fileName = file.name.split('.');
          const fileExt = fileName.length > 1 ? fileName[fileName.length - 1].toLowerCase() : '';

          // 检查文件扩展名是否在允许列表中
          const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
          if (!isTypeOk) {
            this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            this.$refs.upload.clearFiles();
            this.isValid = false;
            return false;
          }

          // 检查是否是图片文件
          const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
          if (imageExtensions.includes(fileExt)) {
            console.log("检测到图片文件，可设置为视频封面");
            this.hasImageInUpload = true;
            this.currentUploadFile = file;
          } else {
            this.hasImageInUpload = false;
            this.isVideoCover = false;
            this.videoCoverName = '';
          }
        }

        // 校检文件大小
        if (this.maxVidSize) {
          const fileName = file.name.split('.');
          const fileExt = fileName.length > 1 ? fileName[fileName.length - 1].toLowerCase() : '';

          if(fileExt === 'mp4'){
            const fileSizeMB = file.size / 1024 / 1024;
            console.log(`检测到MP4文件, 大小: ${fileSizeMB.toFixed(2)}MB`);

            const isLt = fileSizeMB <= this.maxVidSize;
            if (!isLt) {
              this.$modal.msgError(`mp4上传文件大小不能超过 ${this.maxVidSize} MB!`);
              this.$refs.upload.clearFiles();
              this.isValid = false;
              return false;
            }
          } else {
            const fileSizeKB = file.size / 1024;
            console.log(`检测到非MP4文件, 大小: ${fileSizeKB.toFixed(2)}KB`);

            const isLt = fileSizeKB <= this.maxPicSize;
            if (!isLt) {
              this.$modal.msgError(`非mp4上传文件大小不能超过 ${this.maxPicSize} KB!`);
              this.$refs.upload.clearFiles();
              this.isValid = false;
              return false;
            }
          }
        }

        // 验证通过
        console.log("文件验证通过，等待上传");
        this.isValid = true;
        this.number++;
        return false; // 返回false阻止自动上传
      } catch (error) {
        console.error("文件校验出错:", error);
        this.$modal.msgError("文件校验出错: " + (error.message || '未知错误'));
        this.isValid = false;
        return false;
      }
    },

    // 递归搜索对象中的ID
    findIdInObject(obj, idFieldNames) {
      if (!obj || typeof obj !== 'object') return null;

      // 检查当前对象级别
      for (const field of idFieldNames) {
        if (obj[field] !== undefined && obj[field] !== null) {
          return obj[field];
        }
      }

      // 递归搜索嵌套对象
      for (const key in obj) {
        if (obj[key] && typeof obj[key] === 'object') {
          const foundId = this.findIdInObject(obj[key], idFieldNames);
          if (foundId) return foundId;
        }
      }

      return null;
    },

    // 递归搜索对象中的文件名
    findNameInObject(obj, nameFieldNames) {
      if (!obj || typeof obj !== 'object') return null;

      // 检查当前对象级别
      for (const field of nameFieldNames) {
        if (obj[field] !== undefined && obj[field] !== null) {
          return obj[field];
        }
      }

      // 递归搜索嵌套对象
      for (const key in obj) {
        if (obj[key] && typeof obj[key] === 'object') {
          const foundName = this.findNameInObject(obj[key], nameFieldNames);
          if (foundName) return foundName;
        }
      }

      return null;
    },

    // 上传成功回调
    async handleUploadSuccess(res, file) {
      try {
        console.log("文件上传成功, 原始响应对象:", res);
        console.log("文件信息:", file);

        // 调试输出 - 详细检查响应结构
        if (res) {
          console.log("响应状态码:", res.code);
          if (res.data) {
            console.log("响应数据类型:", typeof res.data);
            console.log("响应数据:", res.data);
            if (typeof res.data === 'object') {
              console.log("响应数据字段:", Object.keys(res.data));

              // 尝试输出所有嵌套的字段名
              const allFields = this.collectAllFields(res.data);
              console.log("所有嵌套字段:", allFields);
            }
          } else {
            console.log("响应中没有data字段");
            // 如果没有data字段，检查根级别字段
            console.log("根级别字段:", Object.keys(res));
          }
        }

        // 成功响应处理
        if (res && res.code === 200) {
          console.log("上传成功，准备处理视频封面设置");

          // 获取刚上传文件的信息
          let fileUrl = null;
          let fileName = null;

          // 根据实际响应格式获取文件信息
          // 这个服务器返回的是 {url, fileName, newFileName} 格式
          if (res.url) {
            fileUrl = res.url;
            fileName = res.newFileName || res.originalFilename || file.name;
            console.log("从响应中获取到文件URL:", fileUrl);
            console.log("从响应中获取到文件名:", fileName);
          }

          // 处理视频链接上传
          if (this.uploadForm.videoLink && this.isVideoCover) {
            try {
              console.log("处理视频链接:", this.uploadForm.videoLink);
              
              // 先等待1秒，确保文件已经保存到服务器
              await new Promise(resolve => setTimeout(resolve, 1000));
              
              // 刷新文件列表以获取刚上传的封面图片ID
              await this.refreshFileList();
              
              // 在刷新的文件列表中查找匹配的文件
              const uploadedFile = this.fileList.find(f =>
                (f.url && f.url.includes(fileUrl)) ||
                (f.name === fileName) ||
                (f.name.includes(res.newFileName || ''))
              );
              
              if (uploadedFile) {
                console.log("找到上传的封面图片:", uploadedFile);
                
                // 准备创建视频链接文件
                const videoFileName = this.videoCoverName || "外部视频";
                const videoFileData = {
                  name: videoFileName,
                  type: 1, // 视频类型
                  url: this.uploadForm.videoLink,
                  isDir: 0,
                  parentId: this.queryParams.parentId || 0,
                  remark: "外部视频链接"
                };
                
                console.log("准备创建视频链接文件:", videoFileData);
                
                // 创建视频链接文件
                const addResponse = await addFile(videoFileData);
                
                if (addResponse && addResponse.code === 200) {
                  console.log("视频链接文件创建成功:", addResponse.data);
                  
                  // 设置图片为该视频的封面
                  const updateData = {
                    id: uploadedFile.id,
                    name: uploadedFile.name,
                    oldName: uploadedFile.name,
                    remark: `视频封面：${videoFileName}`
                  };
                  
                  console.log("准备设置封面:", updateData);
                  
                  const updateResponse = await updateFile(updateData);
                  
                  if (updateResponse && updateResponse.code === 200) {
                    this.$modal.msgSuccess("视频链接添加成功，并设置了封面");
                  } else {
                    this.$modal.msgWarning("视频链接添加成功，但封面设置失败");
                  }
                } else {
                  this.$modal.msgError("视频链接添加失败: " + (addResponse?.msg || "未知错误"));
                }
              } else {
                this.$modal.msgError("未找到上传的封面图片");
              }
            } catch (error) {
              console.error("处理视频链接时出错:", error);
              this.$modal.msgError("处理视频链接失败: " + (error.message || "未知错误"));
            }
          }
          // 如果有文件URL但没有文件ID，需要先查询最新的文件列表
          else if (fileUrl && this.isVideoCover && this.videoCoverName) {
            try {
              console.log("准备查询最新文件列表以获取文件ID");

              // 先等待1秒，确保文件已经保存到服务器
              await new Promise(resolve => setTimeout(resolve, 1000));

              // 刷新文件列表
              await this.refreshFileList();

              // 在刷新的文件列表中查找匹配的文件
              // 使用文件URL或文件名匹配
              const uploadedFile = this.fileList.find(f =>
                (f.url && f.url.includes(fileUrl)) ||
                (f.name === fileName) ||
                (f.name.includes(res.newFileName || ''))
              );

              if (uploadedFile) {
                console.log("在文件列表中找到匹配的文件:", uploadedFile);

                // 使用找到的文件ID设置视频封面
                const fileData = {
                  id: uploadedFile.id,
                  name: uploadedFile.name, // 保持原文件名不变
                  remark: `视频封面：${this.videoCoverName}` // 将remark设置为"视频封面+视频名称"
                };

                console.log("准备更新文件信息:", fileData);

                // 更新文件信息
                const response = await updateFile(fileData);
                console.log("更新文件响应:", response);

                if (response && response.code === 200) {
                  this.$modal.msgSuccess("视频封面设置成功");
                  console.log("视频封面设置成功");

                  // 刷新列表以显示更新后的结果
                  this.getList();
                } else {
                  const errorMsg = response && response.msg ? response.msg : '未知错误';
                  this.$modal.msgError("视频封面设置失败: " + errorMsg);
                  console.error("视频封面设置失败:", errorMsg);
                }
              } else {
                console.error("在文件列表中未找到匹配的文件");
                this.$modal.msgWarning(
                  "无法自动设置视频封面。您可以在文件上传完成后，手动点击该图片，" +
                  "使用\"修改\"功能将其备注改为 '视频封面+" + this.videoCoverName + "'"
                );
              }
            } catch (error) {
              console.error("设置视频封面时出错:", error);
              this.$modal.msgError("设置视频封面失败: " + (error.message || '未知错误'));
            }
          } else if (this.isVideoCover && this.videoCoverName) {
            // 没有找到文件URL
            console.error("未找到有效的文件URL，无法设置视频封面");
            this.$modal.msgWarning(
              "无法自动设置视频封面。您可以在文件上传完成后，手动点击该图片，" +
              "使用\"修改\"功能将其备注改为 '视频封面+" + this.videoCoverName + "'"
            );
          }

          // 完成上传过程
          this.uploadedSuccessfully();
        } else {
          // 响应失败
          this.number--;
          this.$modal.closeLoading();
          const errorMsg = res && res.msg ? res.msg : '上传失败，未收到有效响应';
          this.$modal.msgError(errorMsg);
          if (this.$refs.upload && file) {
            this.$refs.upload.handleRemove(file);
          }
          this.uploadedSuccessfully();
        }
      } catch (error) {
        this.$modal.msgError("处理上传成功回调时出错: " + (error.message || '未知错误'));
        console.error("处理上传成功回调时出错:", error);
        this.$modal.closeLoading();
        this.uploadedSuccessfully();
      }
    },

    // 收集对象中的所有字段名（包括嵌套字段）
    collectAllFields(obj, prefix = '', result = []) {
      if (!obj || typeof obj !== 'object') return result;

      Object.keys(obj).forEach(key => {
        const fullPath = prefix ? `${prefix}.${key}` : key;
        result.push(fullPath);

        if (obj[key] && typeof obj[key] === 'object') {
          this.collectAllFields(obj[key], fullPath, result);
        }
      });

      return result;
    },

    // 刷新文件列表（用于查找新上传的文件）
    async refreshFileList() {
      try {
        console.log("刷新文件列表以查找新上传的文件...");
        const params = {
          pageNum: 1,
          pageSize: 50, // 获取足够多的文件以确保包含新上传的文件
          parentId: this.queryParams.parentId || 0
        };

        const response = await listFile(params);
        if (response && response.rows) {
          this.fileList = response.rows;
          this.total = response.total;
          console.log("文件列表刷新成功，获取到", this.fileList.length, "个文件");
          return true;
        } else {
          console.error("刷新文件列表失败，无效响应:", response);
          return false;
        }
      } catch (error) {
        console.error("刷新文件列表出错:", error);
        return false;
      }
    },
    checkboxOndblclick(disk) {
      console.log(disk);
      if (disk.isDir===1) {
        this.queryParams.parentId = disk.id;
        const skip = {
          id: disk.id,
          parentId: disk.parentId,
          name: disk.name
        }
        this.allCrumbsList.push(skip);
        this.allCrumbsList = this.uniqueObjects(this.allCrumbsList);
        this.crumbsList=[];
        this.generateCrumbs(disk.id);
        this.skipList.push(disk.id);
        this.skipList = [...new Set(this.skipList)];
        this.uploadFileUrl = process.env.VUE_APP_BASE_API + "/disk/file/upload/"+disk.id
        this.getList();
      }
    },
    handleSkip(skip) {
      if(skip===0) {
        let index = this.skipList.indexOf(this.queryParams.parentId);
        this.skip(index-1)
      }else {
        let index = this.skipList.indexOf(this.queryParams.parentId);
        this.skip(index+1)
      }
    },
    skip(nextIndex) {
      this.crumbsList=[];
      if (nextIndex<0) {
        this.queryParams.parentId=0;
        this.allCrumbsList=[];
        this.getList();
      }else if (nextIndex>=this.skipList.length) {
        this.queryParams.parentId =0;
        this.allCrumbsList=[];
        this.getList();
      } else {
        this.queryParams.parentId = this.skipList[nextIndex];
        this.generateCrumbs(this.queryParams.parentId);
        this.getList();
      }
    },
    handleShare() {
      this.shareFrom = {
        secretKeyRadio: "1",
        expirationTimeRadio: "1",
        type: "0"
      };
      this.shareResult={}
      this.shareOk = false;
      this.title = "分享"
      this.openShare = true;
    },
    /** 提交按钮 */
    submitShareForm() {

      if (this.shareFrom.type===0 && this.shareFrom.expirationTimeRadio==="2") {
        this.$refs["shareFrom"].validateField("expirationTime",valid => {
          if (!valid) {
            return;
          }
        });
      }
      if (this.shareFrom.type===0 && this.shareFrom.secretKeyRadio==="2") {
        this.$refs["shareFrom"].validateField("secretKey",valid => {
          if (!valid) {
            return;
          }
        });
      }
      this.shareFrom.fileIds = this.ids.join(",");
      addShare(this.shareFrom).then(response => {
        this.shareResult = response.data;
        this.shareOk = true;
      });
    },
    copySuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    copyFailed() {
      this.$modal.msgError("复制失败");
    },
    handleDownload(row) {
      const ids = row.id || this.ids;
      const data = {
        ids: ids.join(",")
      }
      this.$download.downloadZip("/disk/file/download/zip",data,"netdisk.zip");
    },
    //刷新
    dataRefresh() {
      this.ids = [];
      this.checkboxIds = [];
      this.getList();
    },
    mouseEnter(index) {
      this.currentIndex = index;
    },
    mouseLeave(index) {
      this.currentIndex = -1;
    },
    uniqueObjects(arr) {
      const unique = [];
      const seen = new Set();
      arr.forEach(item => {
        const stringifiedItem = JSON.stringify(item);
        if (!seen.has(stringifiedItem)) {
          unique.push(item);
          seen.add(stringifiedItem);
        }
      });
      return unique;
    },
    generateCrumbs(id) {
      if (id===0) {
        this.crumbsList = this.crumbsList.reverse();
        return;
      }
      const crumbs = this.getCrumbsListById(id);
      if (crumbs!=null&&crumbs!=undefined) {
        this.crumbsList.push(crumbs);
        this.generateCrumbs(crumbs.parentId);
      }
    },
    getCrumbsListById(id) {
      return this.allCrumbsList.find(item => {
        return item.id === id;
      });
    },
    skipCrumbs(id) {
      this.queryParams.parentId = id;
      this.crumbsList = [];
      this.generateCrumbs(this.queryParams.parentId);
      this.getList();
    },
    handlePreview(row) {
      if (row.type===1) {
        //视频
        // 检查是否是外部视频链接（通过 remark 判断）
        if (row.remark === "外部视频链接") {
          console.log("预览外部视频链接:", row.url);
          // 处理外部视频链接（可能需要根据具体情况调整）
          if (row.url.includes('youtu') || row.url.includes('bilibili') || row.url.includes('http')) {
            // 对于YouTube、Bilibili等平台的视频，可以在新标签页中打开
            window.open(row.url, '_blank');
          } else {
            // 对于其它链接，使用内部预览器
            this.$router.push({ name: "preview_video", params: {url: row.url, name: row.name, isExternal: true} });
          }
        } else {
          // 内部视频使用原有的预览方式
          this.$router.push({ name: "preview_video", params: {url: row.url, name: row.name} });
        }
      }
    },
    // 新增视频封面选项相关方法
    handleVideoCoverChange() {
      if (!this.isVideoCover) {
        this.videoCoverName = '';
      } else if (this.uploadForm.videoLink) {
        // 如果有视频链接，默认使用链接作为名称的一部分
        this.videoCoverName = '外部视频_' + new Date().getTime();
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    handleConfirmSubmit() {
      try {
        console.log("确认上传文件");

        // 判断是否是纯视频链接上传（没有选择文件，只有链接）
        const hasSelectedFiles = this.$refs.upload && 
                               this.$refs.upload.uploadFiles && 
                               this.$refs.upload.uploadFiles.length > 0;
        
        const hasVideoLink = !!this.uploadForm.videoLink;

        // 如果只有视频链接但没有选择文件
        if (hasVideoLink && !hasSelectedFiles) {
          this.$modal.msgError("外部视频链接必须上传封面图片");
          return;
        }

        // 如果有视频链接，强制设置为视频封面
        if (hasVideoLink) {
          this.isVideoCover = true;
          if (!this.videoCoverName) {
            this.videoCoverName = '外部视频_' + new Date().getTime();
          }
        }

        // 验证视频封面设置
        if (this.isVideoCover && !this.videoCoverName) {
          this.$modal.msgError("请输入要添加封面的视频名称");
          return;
        }

        // 确保上传队列有文件
        if (!hasSelectedFiles) {
          this.$modal.msgError("请先选择要上传的文件");
          return;
        }

        // 显示上传文件列表
        console.log("即将上传的文件:", this.$refs.upload.uploadFiles);

        // 显示加载中状态
        this.$modal.loading("正在上传文件，请稍候...");

        // 设置上传URL，确保包含父目录ID
        const parentId = this.queryParams.parentId || 0;
        this.uploadFileUrl = process.env.VUE_APP_BASE_API + "/disk/file/upload/" + parentId;

        // 确保上传组件已正确初始化
        if (this.$refs.upload) {
          this.$refs.upload.action = this.uploadFileUrl;
          console.log("开始上传文件，上传地址:", this.uploadFileUrl);

          // 手动触发上传
          this.$refs.upload.submit();
        } else {
          throw new Error("上传组件未正确初始化");
        }
      } catch (error) {
        console.error("确认上传文件时出错:", error);
        this.$modal.msgError("确认上传文件时出错: " + (error.message || '未知错误'));
        this.$modal.closeLoading();
      }
    },
    loadIcons(visible) {
      if (visible && this.icons.length === 0) {
        // 转换图标名称格式：ElIconXXX -> el-icon-xxx
        this.icons = Object.keys(ElementIcons)
          .filter(name => name.startsWith('ElIcon'))
          .map(name =>
            'el-icon-' +
            name.replace('ElIcon', '')
              .replace(/([A-Z])/g, '-$1')
              .toLowerCase()
              .substring(1)
          )
      }
    },
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      this.ids = [];
      this.checkboxIds = [];
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.uploadOpen = false;
      this.openDir = false;
      this.updteOpen = false;
      this.openShare = false;
      // 重置上传表单
      this.uploadForm = {
        videoLink: ''
      };
      // 重置封面相关变量
      this.isVideoCover = false;
      this.videoCoverName = '';
      this.hasImageInUpload = false;
      this.currentUploadFile = null;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        oldName: null,
        size: null,
        url: null,
        type: null,
        parentId: null,
        isDir: null,
        orderNum: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
      this.number = 0;
      this.uploadFileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.queryParams.parentId = 0;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 替换原有的handleCheckboxChange方法
    handleSelectionChange(selectedIds) {
      // 获取实际选中的文件对象
      const selectedFiles = this.fileList.filter(file =>
        selectedIds.includes(file.id)
      );

      // 控制按钮状态
      if (selectedFiles.length === 1) {
        const file = selectedFiles[0];
        this.showSetCover = file.isDir === 0 && file.type === 0; // 图片文件判断

        // 根据不同的封面类型设置按钮文本
        if (this.isCoverFile(file)) {
          this.coverButtonText = "普通封面设置";
        } else if (this.isVideoCoverFile(file)) {
          this.coverButtonText = "视频封面设置";
        } else {
          this.coverButtonText = "设置封面";
        }
      } else {
        this.showSetCover = false;
      }

      // 保持原有选择状态更新
      this.ids = selectedIds;
      this.single = selectedIds.length !== 1;
      this.multiple = !selectedIds.length;
    },

    handleCheckboxChange(value) {
      this.ids = this.checkboxIds
      this.single = this.checkboxIds.length!==1
      this.multiple = !this.checkboxIds.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.uploadForm = {
        videoLink: ''
      };
      this.uploadOpen = true;
      this.title = "添加文件";
    },
    /** 新建文件夹按钮操作 */
    handleAddDir() {
      this.reset();
      this.openDir = true;
      this.title = "新建文件夹";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data;
        if(this.form.isDir===1) {
          this.openDir = true;
          this.title = "修改文件夹";
        }else {
          this.updteOpen = true;
          this.title = "修改文件";
        }
      });
    },

    // 设置封面按钮操作改造
    handleSetCover(row) {
      const fileId = row.id || this.ids[0];
      if (!fileId) return this.$modal.msgError("请选择文件");

      // 获取选中的文件
      const targetFile = this.fileList.find(f => f.id === fileId);
      if (!targetFile) return this.$modal.msgError("未找到选中的文件");

      // 检查是否是图片
      if (targetFile.isDir !== 0 || targetFile.type !== 0) {
        return this.$modal.msgError("只能将图片设置为封面");
      }

      // 检查是否已经是普通封面或视频封面
      const isRegularCover = this.isCoverFile(targetFile);
      const isVideoCover = this.isVideoCoverFile(targetFile);

      // 如果已经是某种封面，提供取消选项
      if (isRegularCover || isVideoCover) {
        const coverType = isRegularCover ? '普通封面' : '视频封面';
        this.$confirm(`该图片已设置为${coverType}，您想执行什么操作？`, '封面设置', {
          confirmButtonText: `取消${coverType}`,
          cancelButtonText: '返回',
          distinguishCancelAndClose: true,
          closeOnClickModal: false,
          type: 'info'
        }).then(() => {
          // 取消当前封面
          if (isRegularCover) {
            this.processRegularCover(fileId, true);
          } else if (isVideoCover) {
            this.processVideoCover(fileId, true);
          }
        }).catch(() => {});
        return;
      }

      // 如果不是任何封面，提供设置选项
      this.$confirm('请选择要设置的封面类型', '设置封面', {
        confirmButtonText: '普通封面',
        cancelButtonText: '视频封面',
        distinguishCancelAndClose: true,
        closeOnClickModal: false,
        type: 'info',
        showClose: true
      }).then(() => {
        // 设置为普通封面
        this.processRegularCover(fileId, false);
      }).catch(action => {
        if (action === 'cancel') {
          // 用户选择设置视频封面
          this.$prompt('请输入要添加封面的视频名称', '设置视频封面', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '视频名称'
          }).then(({ value }) => {
            if (value) {
              this.processVideoCover(fileId, false, value);
            }
          }).catch(() => {});
        }
      });
    },

    // 处理普通封面
    async processRegularCover(fileId, isRemove = false) {
      try {
        const targetFile = this.fileList.find(f => f.id === fileId);
        if (!targetFile) return this.$modal.msgError("未找到文件");

        // 如果是取消操作
        if (isRemove) {
          const oldName = targetFile.name;
          const newName = oldName.replace('封面：', '');

          // 构建更新数据
          const updateData = {
            id: fileId,
            name: newName,
            oldName: oldName
          };

          // 应用更新
          const response = await updateFile(updateData);

          if (response.code === 200) {
            this.$modal.msgSuccess("已取消普通封面设置");
            // 更新本地数据
            targetFile.name = newName;
            this.getList(); // 刷新列表
          } else {
            this.$modal.msgError("取消普通封面失败: " + (response.msg || '未知错误'));
          }
          return;
        }

        // 查找当前目录中是否已存在普通封面
        const existingCover = this.fileList.find(file =>
          file.id !== fileId &&
          file.isDir === 0 &&
          this.isCoverFile(file) &&
          file.parentId === targetFile.parentId // 确保在同一目录
        );

        // 存在封面，询问是否替换
        if (existingCover) {
          const confirmResult = await this.$confirm(
            `当前目录已存在普通封面"${existingCover.name}"，是否替换？`,
            '替换封面',
            {
              confirmButtonText: '替换',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).catch(() => false);

          // 用户取消了替换
          if (!confirmResult) return;

          // 用户确认替换，先取消原有封面
          try {
            const removeResponse = await updateFile({
              id: existingCover.id,
              name: existingCover.name.replace('封面：', ''),
              oldName: existingCover.name
            });

            if (removeResponse.code !== 200) {
              this.$modal.msgError("取消原有封面失败: " + (removeResponse.msg || '未知错误'));
              return;
            }
          } catch (error) {
            this.$modal.msgError("取消原有封面失败: " + (error.message || '未知错误'));
            return;
          }
        }

        // 设置当前文件为普通封面
        const oldName = targetFile.name;
        const newName = oldName.startsWith('封面：') ? oldName : `封面：${oldName}`;

        // 构建更新数据
        const updateData = {
          id: fileId,
          name: newName,
          oldName: oldName
        };

        // 应用更新
        const response = await updateFile(updateData);

        if (response.code === 200) {
          this.$modal.msgSuccess("普通封面设置成功");
          // 更新本地数据
          targetFile.name = newName;
          this.getList(); // 刷新列表
        } else {
          this.$modal.msgError("设置普通封面失败: " + (response.msg || '未知错误'));
        }
      } catch (error) {
        this.$modal.msgError("操作失败：" + (error.message || '未知错误'));
        console.error("处理普通封面变更时出错:", error);
      }
    },

    // 处理视频封面
    async processVideoCover(fileId, isRemove = false, videoName = '') {
      try {
        const targetFile = this.fileList.find(f => f.id === fileId);
        if (!targetFile) return this.$modal.msgError("未找到文件");

        // 构建更新数据
        const updateData = {
          id: fileId,
          name: targetFile.name,  // 添加 name 字段
          oldName: targetFile.name  // 添加 oldName 字段
        };

        if (isRemove) {
          // 取消封面 - 清空remark
          updateData.remark = '';

          // 应用更新
          const response = await updateFile(updateData);

          if (response.code === 200) {
            this.$modal.msgSuccess("已取消视频封面设置");
            // 更新本地数据
            targetFile.remark = '';
            this.getList(); // 刷新列表
          } else {
            this.$modal.msgError("取消视频封面失败: " + (response.msg || '未知错误'));
          }
        } else {
          // 设置为视频封面 - 修改remark
          updateData.remark = `视频封面：${videoName}`;

          // 应用更新
          const response = await updateFile(updateData);

          if (response.code === 200) {
            this.$modal.msgSuccess("视频封面设置成功");
            // 更新本地数据
            targetFile.remark = `视频封面：${videoName}`;
            this.getList(); // 刷新列表
          } else {
            this.$modal.msgError("设置视频封面失败: " + (response.msg || '未知错误'));
          }
        }
      } catch (error) {
        this.$modal.msgError("操作失败：" + (error.message || '未知错误'));
        console.error("处理视频封面变更时出错:", error);
      }
    },

    submitDirForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.parentId = this.queryParams.parentId;
          this.form.isDir = 1;
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openDir = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openDir = false;
              this.getList();
            });
          }
        }
      });
    },

    // 添加封面加载失败处理
    handleCoverError() {
      this.form.remark = ''
      this.$modal.msgError("封面加载失败，请重新上传")
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.updteOpen = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.updteOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文件编号为"' + ids + '"的数据项？').then(function() {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('disk/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    // 上传结束处理
    uploadedSuccessfully() {
      console.log("上传过程结束，刷新文件列表");
      if (this.number > 0) {
        this.number = 0;
        this.uploadFileList = [];
        this.uploadOpen = false;
        // 重置封面相关变量
        this.isVideoCover = false;
        this.videoCoverName = '';
        this.hasImageInUpload = false;
        this.currentUploadFile = null;
        this.getList();
        this.$modal.closeLoading();
      } else {
        this.$modal.closeLoading();
      }
    },
    // 检查文件是否为视频封面
    isVideoCoverFile(file) {
      return file && file.remark && file.remark.startsWith('视频封面：');
    },

    // 从文件备注中提取视频名称
    getVideoCoverName(file) {
      if (file && file.remark && file.remark.startsWith('视频封面：')) {
        return file.remark.substring('视频封面：'.length); // 正确提取视频名称
      }
      return '';
    },

    // 根据视频名称查找对应的封面图片
    findVideoCover(videoName) {
      if (!videoName || !this.fileList) return null;

      // 在文件列表中查找remark为"视频封面：视频名称"的图片
      return this.fileList.find(file =>
        file.isDir === 0 &&
        file.type === 0 &&
        file.remark &&
        file.remark === `视频封面：${videoName}`
      );
    },
  }
};
</script>
<style lang="scss" scoped>

/* 添加视频链接输入字段样式 */
.el-form-item__tip {
  color: #909399;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}

.el-alert {
  display: flex;
  align-items: center;
  border-radius: 4px;
}

.el-alert__title {
  font-size: 13px;
  line-height: 18px;
  margin-left: 8px;
}

/* 添加封面预览样式 */
.cover-preview {
  position: relative;
  width: 160px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;

  &:hover {
    border-color: #409eff;
  }

  .cover-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #8c939d;
  }
}


.file-name {
  width: 80px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  text-align: center;
  margin-top: 5px;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  i {
    font-size: 24px;
    padding: 8px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: scale(1.2);
      color: #409eff;
    }
  }
}


/* 封面高亮样式 */
.cover-highlight {
  position: relative;
  border: 2px solid #409EFF !important;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,.1);

  &::after {
    content: "封面";
    position: absolute;
    top: -10px;
    right: -10px;
    background: #409EFF;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 2;
  }
}

/* 视频封面高亮样式 */
.video-cover-highlight {
  position: relative;
  border: 2px solid #67C23A !important;
  box-shadow: 0 2px 12px 0 rgba(103,194,58,.1);
}

/* 封面图标样式 */
.cover-icon {
  position: absolute;
  top: 5px;
  left: 5px;
  color: #409EFF;
  font-size: 20px;
  z-index: 2;
  background: rgba(255,255,255,.8);
  border-radius: 50%;
  padding: 3px;
}

/* 视频封面图标样式 */
.video-cover-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  color: #67C23A;
  font-size: 20px;
  z-index: 2;
  background: rgba(255,255,255,.8);
  border-radius: 50%;
  padding: 3px;
}

/* 视频封面标签样式 */
.video-cover-label {
  position: absolute;
  bottom: 25px;
  left: 0;
  right: 0;
  background: rgba(103,194,58,.8);
  color: white;
  padding: 2px 5px;
  font-size: 12px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
}

@keyframes coverPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.cover-animation {
  animation: coverPulse 1s ease-in-out;
}








.cover-indicator {
  position: absolute;
  left: 5px;
  top: 5px;
  color: #67C23A;
  font-size: 16px;
  z-index: 2;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 单个图标样式 */
.icon-item {
  cursor: pointer;
  transition: all 0.2s;
  padding: 8px;
  border-radius: 4px;
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}

.icon-content {
  font-size: 24px;
  color: #606266;
  transition: all 0.2s;
}

/* 交互状态 */
.icon-item:hover {
  background-color: #f5f7fa;
}

.icon-item:hover .icon-content {
  color: #409eff;
  transform: scale(1.2);
}

.icon-item.active {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}

.selected-icon {
  font-size: 18px;
  color: #409eff;
  margin-right: 5px;
}
.el-select-dropdown__item {
  padding: 0 20px !important;
  height: 36px !important;
  line-height: 36px !important;
}
.icon-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 10px;
  margin-top: 10px;
}
.Extra-Text {
  width: 300px;
  height: 80px;
  border: 2px solid #dfe6ec;
  font-size: 12px;
  position: relative;
  top: -150px;
  left: 1px;
  background-color: #bfcbd9;
  text-align: center;
  color: #ffffff;
  z-index: 9999;
  border-radius: 20px;
}
.icon-input-wrapper {
  margin-bottom: 15px;
  position: relative;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
  gap: 12px;
  border: 1px solid #ebeef5;
  padding: 12px;
  border-radius: 4px;
}

.icon-grid div {
  cursor: pointer;
  text-align: center;
  padding: 5px;
  border-radius: 4px;
}

.icon-grid div:hover {
  background-color: #f5f7fa;
}

.icon-grid div.active {
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
}

/* 外部链接图标样式 */
.external-link-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  color: #409EFF;
  font-size: 20px;
  z-index: 2;
  background: rgba(255,255,255,.8);
  border-radius: 50%;
  padding: 3px;
}
</style>
